#include <stdio.h>

const m = 10 ;
int flag = 0 ;

struct entry
{
 char user[20] ;
 char password[20] ;
} *table[10] ;

void formhashtable(char a[20], char b[20], int sum, int i)
{
 int index, la, lb ;
 la = strlen(a) ;
 lb = strlen(b) ;
 index = (sum+i)%m ;
 printf("sum:%d , index = %d", sum, index) ;
 if(table[index]==NULL)
 {
  table[index] = malloc(sizeof(struct entry)) ;
  int k ;
  for(k=0;k<la;k++)
  {
   table[index]->user[k] = a[k] ;
  }
  
  for(k=0;k<lb;k++)
  {
   table[index]->password[k] = b[k] ;
  }
 }
 else
 {
  formhashtable(a, b, sum, (i+1)) ;
 }
}


void accesscheck(char a[20], char b[20], int sum, int i)
{
 int k, index, la, lb, luser, lpassword, fc, fp ;
 fc = 1 ;
 fp = 0 ;
 la = strlen(a) ;
 lb = strlen(b) ;
 luser = strlen(table[index]->user) ;
 lpassword = strlen(table[index]->password) ;
 index = (sum+i)%m ;
 if(table[index]!=NULL && la==luser)
 {
  fc = 2 ;
  for(k=0;k<la;k++)
  {
  if(table[index]->user[k]!=a[k])
  {
   fc = 1 ;
  }
  }
  if(fc == 2 && lpassword==lb)
  {
   fp = 2 ;
   fc = 2 ;
   for(k=0;k<lb;k++)
   {
   if(table[index]->password[k]!=b[k])
   {
    fp = 1 ;
   }
   }
  }
 }
 if(fc == 1 && fp == 0)
 {
  printf("\nUSERNAME NOT FOUND!\n") ;
 }
 else
  if(fc == 2 && fp == 1)
  {
   printf("\nINCORRECT PASSWORD!\n") ;
  }
  else
   if(fp==2 && fc==2)
   {
    printf("\nACCESS GRANTED!\n") ;
    flag = 1 ;
   }
   else
   {
    accesscheck(a, b, sum, (i+1)) ;
   }
 }

int main()
{
 int i, l, luin, j, t, sum, h, w ;
 char a[20], b[20], uin[20], pin[20] ;
 for(w=0;w<10;w++)
 {
  table[w] = NULL ;
 }
 FILE *f ;
 f = fopen("passwords.txt", "r") ;
 for(i=0;i<10;i++)
 {
  fscanf(f,"%s %s", &a, &b) ;
  l = strlen(a) ;
  sum = 0 ;
  for(j=0;j<l;j++)
  {
   t = a[j] ;
   t = t*j ;
   sum = sum + t ;
  }
  formhashtable(a, b, sum, 0) ;
 }
 printf("\n") ;
 int trial ;
 trial = 3 ;
 do
 {
  printf("\n\n Enter the username: ") ;
  scanf("%s", &uin) ;
  printf("\n\n Enter the password: ") ;
  scanf("%s", &pin) ;
  luin = strlen(uin) ;
  sum = 0 ;
  for(i=0;i<luin;i++)
  {
   t = uin[i] ;
   t = t*i ;
   sum = sum + t ;
  }
  flag = 0 ;
  accesscheck(uin, pin, sum, 0) ;
  trial-- ;
  if(flag == 1)
  {
   break ;
  }
 } while(trial>0) ;
 if(trial==0 && flag!=1)
 {
  printf("\n\n\n TOO MANY TRIES! ACCESS FORBIDDEN!\n") ;
 }
}
